//
//  AppDelegate.m
//  HelpThePoor
//
//  Created by van7ish on 2016/11/25.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "AppDelegate.h"
#import "HomeViewController.h"
#import "CloudViewController.h"
#import "CountyViewController.h"
#import "SpreadViewController.h"
#import "MineViewController.h"
#import "AFNetworking.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

+(AppDelegate *)shareDelegate{
    AppDelegate *delegate =(id)[[UIApplication sharedApplication] delegate];
    return delegate;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    HomeViewController *homeVC = [[HomeViewController alloc] init];
    ZRNavigationController *nav1 = [[ZRNavigationController alloc] initWithRootViewController:homeVC];
    CloudViewController *cloudVC = [[CloudViewController alloc] init];
    ZRNavigationController *nav2 = [[ZRNavigationController alloc] initWithRootViewController:cloudVC];
    CountyViewController *CountyVC = [[CountyViewController alloc] init];
    ZRNavigationController *nav3 = [[ZRNavigationController alloc] initWithRootViewController:CountyVC];
    SpreadViewController *spreadVC = [[SpreadViewController alloc] init];
    ZRNavigationController *nav4 = [[ZRNavigationController alloc] initWithRootViewController:spreadVC];
    MineViewController *mineVC = [[MineViewController alloc] init];
    ZRNavigationController *nav5 = [[ZRNavigationController alloc] initWithRootViewController:mineVC];
    
    NSArray *viewControllers = @[nav1, nav2, nav3, nav4, nav5];
    
    self.tabBar = [[ZRTabBarController alloc] init];
    self.tabBar.viewControllers = viewControllers;
    self.window.rootViewController = self.tabBar;
    [self.window makeKeyAndVisible];
    
    //判断是否已登录
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"user"]) {
        NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
        NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
        [AppDelegate shareDelegate].userModel = [UserModel modelWithDictionary:userDic];
    }
    
    [SVProgressHUD setBackgroundColor:[UIColor blackColor]];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    
    [self addNotBackUpiCloud];//不自动备份documents文件到iCloud
    
    [self afnReachability];
    
    [[NSFileManager defaultManager] createDirectoryAtPath:BooksPath withIntermediateDirectories:NO attributes:nil error:nil];
    //创建Magazines文件夹用来存储用户下载的期刊。
    [[NSFileManager defaultManager] createDirectoryAtPath:MagazinesPath withIntermediateDirectories:NO attributes:nil error:nil];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {

}


- (void)applicationDidEnterBackground:(UIApplication *)application {

}


- (void)applicationWillEnterForeground:(UIApplication *)application {

}


- (void)applicationDidBecomeActive:(UIApplication *)application {

}

- (void)applicationWillTerminate:(UIApplication *)application {

}

#pragma mark - 支持转屏

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    if (_allowRotation == 1) {
        return UIInterfaceOrientationMaskAll;
    }else{
        return (UIInterfaceOrientationMaskPortrait);
    }
}

- (void)addNotBackUpiCloud
{
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString* docPath = [documentPaths objectAtIndex:0];
    [self addSkipBackupAttributeToItemAtURL:docPath];
}
/**
 *屏蔽iOS文件不备份到icloud
 */
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSString *)filePathString
{
    NSURL* URL = [NSURL fileURLWithPath:filePathString];
    assert([[NSFileManager defaultManager] fileExistsAtPath:[URL path]]);
    
    NSError *error = nil;
    
    BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES] forKey: NSURLIsExcludedFromBackupKey error:&error];
    if(!success){
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}

- (void)afnReachability{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //网络改变
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
        [manager GET:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
            DLog(@"Success: %@", responseObject);
            if ([[responseObject objectForKey:@"code"] integerValue] == 0) {
                [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"data"][@"ip"] forKey:@"ipAddress"];
            } else {
                [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"ipAddress"];
            }
        } failure:^(NSURLSessionTask *operation, NSError *error) {
            DLog(@"Error: %@", error);
        }];
        
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

@end
